// 游戏配置
const config = {
    canvasWidth: 400,
    canvasHeight: 400,
    gridSize: 20,
    initialSpeed: 150,
    speedIncrease: 10
};

// 游戏状态
let gameState = {
    snake: [],
    food: {},
    direction: 'right',
    nextDirection: 'right',
    score: 0,
    highScore: 0,
    isRunning: false,
    isPaused: false,
    gameLoop: null,
    currentSpeed: config.initialSpeed
};

// DOM元素
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const currentScoreEl = document.getElementById('current-score');
const highScoreEl = document.getElementById('high-score');
const startBtn = document.getElementById('start-btn');
const pauseBtn = document.getElementById('pause-btn');
const restartBtn = document.getElementById('restart-btn');
const gameOverModal = document.getElementById('game-over-modal');
const finalScoreEl = document.getElementById('final-score');
const playAgainBtn = document.getElementById('play-again-btn');

// 初始化游戏
function initGame() {
    loadHighScore();
    resetGame();
    drawInitialState();
}

// 重置游戏
function resetGame() {
    gameState = {
        snake: [{x: 5, y: 5}, {x: 4, y: 5}, {x: 3, y: 5}],
        food: generateFood(),
        direction: 'right',
        nextDirection: 'right',
        score: 0,
        highScore: gameState.highScore,
        isRunning: false,
        isPaused: false,
        gameLoop: null,
        currentSpeed: config.initialSpeed
    };
    
    updateScore();
    drawInitialState();
}

// 生成食物
function generateFood() {
    let newFood;
    do {
        newFood = {
            x: Math.floor(Math.random() * (config.canvasWidth / config.gridSize)),
            y: Math.floor(Math.random() * (config.canvasHeight / config.gridSize))
        };
    } while (gameState.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    
    return newFood;
}

// 绘制初始状态
function drawInitialState() {
    ctx.clearRect(0, 0, config.canvasWidth, config.canvasHeight);
    
    // 绘制网格
    ctx.strokeStyle = '#e9ecef';
    ctx.lineWidth = 1;
    for (let i = 0; i <= config.canvasWidth; i += config.gridSize) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, config.canvasHeight);
        ctx.stroke();
    }
    for (let i = 0; i <= config.canvasHeight; i += config.gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(config.canvasWidth, i);
        ctx.stroke();
    }
    
    // 绘制蛇
    drawSnake();
    
    // 绘制食物
    drawFood();
}

// 绘制蛇
function drawSnake() {
    gameState.snake.forEach((segment, index) => {
        if (index === 0) {
            // 蛇头
            ctx.fillStyle = '#28a745';
        } else {
            // 蛇身
            ctx.fillStyle = '#20c997';
        }
        
        ctx.fillRect(
            segment.x * config.gridSize,
            segment.y * config.gridSize,
            config.gridSize - 2,
            config.gridSize - 2
        );
    });
}

// 绘制食物
function drawFood() {
    ctx.fillStyle = '#dc3545';
    ctx.beginPath();
    ctx.arc(
        gameState.food.x * config.gridSize + config.gridSize / 2,
        gameState.food.y * config.gridSize + config.gridSize / 2,
        config.gridSize / 2 - 2,
        0,
        2 * Math.PI
    );
    ctx.fill();
}

// 更新游戏状态
function updateGame() {
    if (gameState.isPaused) return;
    
    // 更新方向
    gameState.direction = gameState.nextDirection;
    
    // 计算新的蛇头位置
    const head = {...gameState.snake[0]};
    
    switch (gameState.direction) {
        case 'up':
            head.y -= 1;
            break;
        case 'down':
            head.y += 1;
            break;
        case 'left':
            head.x -= 1;
            break;
        case 'right':
            head.x += 1;
            break;
    }
    
    // 检查碰撞
    if (checkCollision(head)) {
        gameOver();
        return;
    }
    
    // 添加新的蛇头
    gameState.snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === gameState.food.x && head.y === gameState.food.y) {
        gameState.score += 10;
        gameState.food = generateFood();
        gameState.currentSpeed = Math.max(50, gameState.currentSpeed - config.speedIncrease);
        updateScore();
    } else {
        // 如果没有吃到食物，移除尾部
        gameState.snake.pop();
    }
    
    // 重新绘制
    drawInitialState();
}

// 检查碰撞
function checkCollision(head) {
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= config.canvasWidth / config.gridSize ||
        head.y < 0 || head.y >= config.canvasHeight / config.gridSize) {
        return true;
    }
    
    // 检查自身碰撞
    return gameState.snake.some(segment => segment.x === head.x && segment.y === head.y);
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    clearInterval(gameState.gameLoop);
    
    if (gameState.score > gameState.highScore) {
        gameState.highScore = gameState.score;
        saveHighScore();
    }
    
    finalScoreEl.textContent = gameState.score;
    gameOverModal.classList.remove('hidden');
    
    startBtn.disabled = true;
    pauseBtn.disabled = true;
    restartBtn.disabled = false;
}

// 开始游戏
function startGame() {
    if (gameState.isRunning) return;
    
    gameState.isRunning = true;
    gameState.isPaused = false;
    
    startBtn.disabled = true;
    pauseBtn.disabled = false;
    restartBtn.disabled = false;
    
    gameState.gameLoop = setInterval(updateGame, gameState.currentSpeed);
}

// 暂停/继续游戏
function togglePause() {
    if (!gameState.isRunning) return;
    
    gameState.isPaused = !gameState.isPaused;
    
    if (gameState.isPaused) {
        pauseBtn.textContent = '继续';
        clearInterval(gameState.gameLoop);
    } else {
        pauseBtn.textContent = '暂停';
        gameState.gameLoop = setInterval(updateGame, gameState.currentSpeed);
    }
}

// 重新开始游戏
function restartGame() {
    gameOverModal.classList.add('hidden');
    resetGame();
    startGame();
}

// 更新分数显示
function updateScore() {
    currentScoreEl.textContent = gameState.score;
    highScoreEl.textContent = gameState.highScore;
}

// 保存最高分
function saveHighScore() {
    localStorage.setItem('snakeHighScore', gameState.highScore);
}

// 加载最高分
function loadHighScore() {
    const saved = localStorage.getItem('snakeHighScore');
    if (saved) {
        gameState.highScore = parseInt(saved);
        highScoreEl.textContent = gameState.highScore;
    }
}

// 事件监听
document.addEventListener('keydown', (e) => {
    if (!gameState.isRunning || gameState.isPaused) return;
    
    switch (e.key) {
        case 'ArrowUp':
            if (gameState.direction !== 'down') {
                gameState.nextDirection = 'up';
            }
            break;
        case 'ArrowDown':
            if (gameState.direction !== 'up') {
                gameState.nextDirection = 'down';
            }
            break;
        case 'ArrowLeft':
            if (gameState.direction !== 'right') {
                gameState.nextDirection = 'left';
            }
            break;
        case 'ArrowRight':
            if (gameState.direction !== 'left') {
                gameState.nextDirection = 'right';
            }
            break;
    }
});

startBtn.addEventListener('click', startGame);
pauseBtn.addEventListener('click', togglePause);
restartBtn.addEventListener('click', restartGame);
playAgainBtn.addEventListener('click', restartGame);

// 防止方向键滚动页面
document.addEventListener('keydown', (e) => {
    if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
        e.preventDefault();
    }
});

// 初始化游戏
initGame();
